import { loginAPI, getInfoAPI, getDetailUserInfoAPI } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      state.token = data
      // 存token
      setToken(data)
    },
    // 删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户信息
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 用户登录，得到token
    async loginAction(context, data) {
      // 得到token
      const res = await loginAPI(data)
      // console.log('登录请求', res)
      // 触发mutation
      context.commit('setToken', res)
    },
    // 获取用户信息
    async getUserInfoAction(context) {
      const res = await getInfoAPI()
      // console.log(res)
      const res2 = await getDetailUserInfoAPI(res.userId)
      // console.log(res2)
      context.commit('setUserInfo', { ...res, ...res2 })
    },
    // 退出，清除用户信息
    quitAction(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
